<template>
  <template v-if="renderType === 'dropdown'">
    <component v-for="btn in renderButtons" :is="btn" />
  </template>

  <template v-else>
    <div
      :class="[
        'bc-action-buttons',
        props.layout && `bc-action-buttons-layout-${props.layout}`,
        !!renderType && 'bc-action-buttons-group',
        !!inline && 'bc-action-buttons-inline',
        !!wrap && 'bc-action-buttons-wrap',
        !!reverse && 'bc-action-buttons-reverse',
      ]"
      v-bind="attrs"
    >
      <component v-for="btn in renderButtons" :is="btn" />
    </div>
    <Space v-if="renderType && spaceType !== 'none'" :type="spaceType" />
  </template>
</template>

<script setup>
import { ref, h, computed, useAttrs } from 'vue';
import { ElDropdown, ElDropdownMenu, ElDropdownItem, ElTooltip } from 'element-plus';
import { buttonSetter } from '@/components/@setter';
import Space from './space.vue';

const props = defineProps({
  blockName: String,
  type: String,
  space: String,
  inline: Boolean,
  wrap: Boolean,
  reverse: Boolean,
  layout: String,
  buttons: Array,
  baseProps: Object,
  renderType: String,
  eventData: Object,
  eventMap: Object,
});

const attrs = useAttrs();
const spaceType = ref(null);
const lastIndex = computed(() => props.buttons.length - 1);

const eventFunction = (item, name) => {
  const event = typeof item[name] === 'function' ? item[name] : props.eventMap[item[name] || item.key];
  return typeof event === 'function' ? (...args) => event(...args, item, props.eventData) : null;
};

const handleDropdownMenu = (buttons) => {
  return buttons.map((btn) => ({
    ...btn.props,
    key: btn.key,
    command: () => eventFunction(btn, 'onClick')(),
  }));
};

const renderButtons = props.buttons.map((item, index) => {
  if (Array.isArray(item)) {
    const [group, ...subButtons] = item;
    return h(RenderButtons, {
      type: props.type,
      space: index === lastIndex.value ? 'none' : props.space,
      buttons: subButtons,
      baseProps: props.baseProps,
      renderType: group.type,
      eventData: props.eventData,
      eventMap: props.eventMap,
      key: group.key,
    });
  }

  const btnType = item.type || props.type || 'a';
  const buttonType = buttonSetter.get(btnType);
  if (!buttonType) throw new Error('Unknown button type:' + btnType);

  const buttonProps = {
    ...props.baseProps?.[btnType],
    ...(item.props || props.eventData),
    id: ['button', props.blockName, item.key].filter(Boolean).join('_'),
  };

  let button = h(buttonType.component, buttonProps);

  if (item.render) {
    button = item.render(buttonProps, button);
  }

  if (item.dropdown) {
    button = h(
      ElDropdown,
      {
        ...props.baseProps?.dropdown,
        ...item.props,
      },
      {
        default: () => button,
        dropdown: () =>
          h(
            ElDropdownMenu,
            {
              onCommand: (command) => command(),
            },
            handleDropdownMenu(item.items).map((menuItem) =>
              h(ElDropdownItem, { command: menuItem.command, key: menuItem.key }, menuItem.label),
            ),
          ),
      },
    );
  }

  if (item.tip) {
    button = h(
      ElTooltip,
      {
        ...props.baseProps?.tip,
        content: typeof item.tip === 'string' ? item.tip : item.tip.title,
        ...(typeof item.tip === 'object' ? item.tip : {}),
      },
      () => button,
    );
  }

  spaceType.value = item.space || props.space || (btnType === 'a' ? 'divider' : 'empty');

  return [
    h('div', { key: item.key }, button),
    index !== lastIndex.value && props.space !== 'none' && h(Space, { type: spaceType.value }),
  ];
});
</script>

<style lang="less">
.bc-action-buttons {
  display: flex;
  align-items: center;

  &-inline {
    display: inline-flex;
  }

  &-wrap {
    flex-wrap: wrap;
  }

  &-layout {
    &-start {
      justify-content: flex-start;
    }
    &-center {
      justify-content: center;
    }
    &-end {
      justify-content: flex-end;
    }
    &-around {
      justify-content: space-around;
    }
    &-between {
      justify-content: space-between;
    }
    &-evenly {
      justify-content: space-evenly;
    }
  }

  &-reverse {
    flex-direction: row-reverse;
  }

  // &-group {
  //   .ant-btn:hover {
  //     z-index: 3;
  //   }

  //   .ant-btn,
  //   .ant-btn.ant-btn-circle,
  //   .ant-btn.ant-btn-round {
  //     border-radius: 0;
  //   }

  //   .ant-btn + .ant-btn {
  //     margin-left: -1px;
  //   }

  //   .ant-btn:nth-of-type(1) {
  //     border-top-left-radius: var(--size-border-radius);
  //     border-bottom-left-radius: var(--size-border-radius);
  //   }

  //   .ant-btn:nth-last-of-type(1) {
  //     border-top-right-radius: var(--size-border-radius);
  //     border-bottom-right-radius: var(--size-border-radius);
  //   }

  //   .ant-btn.ant-btn-round:nth-of-type(1) {
  //     border-top-left-radius: 24px;
  //     border-bottom-left-radius: 24px;
  //   }

  //   .ant-btn.ant-btn-round:nth-last-of-type(1) {
  //     border-top-right-radius: 24px;
  //     border-bottom-right-radius: 24px;
  //   }
  // }

  // .ant-tag {
  //   margin-inline-end: 0;
  // }
}
</style>
